package org.jeecg.modules.appuser.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sun.xml.internal.bind.v2.TODO;
import lombok.Synchronized;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.appuser.constant.PayTypeConstant;
import org.jeecg.modules.appuser.entity.*;
import org.jeecg.modules.appuser.mapper.TbUserGameBuidingMapper;
import org.jeecg.modules.appuser.service.*;
import org.jeecg.modules.mall.entity.TbMnUser;
import org.jeecg.modules.mall.service.ITbMnUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 盖楼游戏基础表
 * @Author: jeecg-boot
 * @Date: 2020-05-18
 * @Version: V1.0
 */
@Service
public class TbUserGameBuidingServiceImpl extends ServiceImpl<TbUserGameBuidingMapper, TbUserGameBuiding> implements ITbUserGameBuidingService {

    @Autowired
    @Lazy(true)
    private ITbMnUserService tbMnUserService;

    @Autowired
    private ITbUserUpgradeConfigService tbUserUpgradeConfigService;

    @Autowired
    private ITbUserSqtService tbUserSqtService;

    @Autowired
    @Lazy(true)
    private ITbUserWalletService tbUserWalletService;


    @Autowired
    private ITbUserSqtDetailService tbUserSqtDetailService;

    @Autowired
    private ITbUserWalletDetailService tbUserWalletDetailService;
    @Autowired
    private ITbUserVipService tbUserVipService;


    @Override
    public Result<?> getUserGradeData(String user_id) {
        Map<String, Object> resultMap = new HashMap<>();
        TbMnUser tbMnUser = tbMnUserService.getById(user_id);
        if (null == tbMnUser) {
            return Result.error("用户不存在");
        }
        Map<String, Object> able_map = new HashMap<>();

        int inivate_number = 0;
        BigDecimal profit = new BigDecimal("0");
        able_map.put("profit", profit);
        able_map.put("inivate_number", inivate_number);
        getAbleInivateData(tbMnUser, able_map);
        //vip配置
        List<TbUserVip> tbUserVipList = tbUserVipService.list();
        resultMap.put("tbUserVipList", tbUserVipList);

        resultMap.put("tbMnUser", tbMnUser);
        resultMap.put("inivate_number", able_map.get("inivate_number"));
        resultMap.put("profit", able_map.get("profit"));
        //以获得收益，查询余额
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", user_id);
        return Result.ok(resultMap);
    }

    private void getAbleInivateData(TbMnUser tbMnUser, Map<String, Object> able_map) {
            int inivate_number = (int) able_map.get("inivate_number");
            BigDecimal profit = (BigDecimal) able_map.get("profit");
            QueryWrapper inVitequeryWrapper = new QueryWrapper();
            String inviteCode = tbMnUser.getInviteCode();
            inVitequeryWrapper.eq("register_code", inviteCode);
            //邀请的人数
            List<TbMnUser> tbMnUserList = tbMnUserService.list(inVitequeryWrapper);

            if (null != tbMnUserList && tbMnUserList.size() > 0) {
                for (TbMnUser mnUser : tbMnUserList) {
                    QueryWrapper userWalletQueryWrapper = new QueryWrapper();
                    userWalletQueryWrapper.eq("user_id", mnUser.getId());
                    userWalletQueryWrapper.eq("pay_from", PayTypeConstant.PAYFORM_REBATE);
                    List<TbUserWalletDetail> tbUserWalletDetailList = tbUserWalletDetailService.list(userWalletQueryWrapper);
                    for (TbUserWalletDetail tbUserWalletDetail : tbUserWalletDetailList) {
                        profit.add(tbUserWalletDetail.getBalance());
                    }
                    inivate_number += 1;
                    able_map.put("profit", profit);
                    able_map.put("inivate_number", inivate_number);
                    getAbleInivateData2(mnUser, able_map);
                }

        }

}

    private void getAbleInivateData2(TbMnUser tbMnUser, Map<String, Object> able_map) {
        int inivate_number = (int) able_map.get("inivate_number");
        BigDecimal profit = (BigDecimal) able_map.get("profit");
        QueryWrapper inVitequeryWrapper = new QueryWrapper();
        String inviteCode = tbMnUser.getInviteCode();
        inVitequeryWrapper.eq("register_code", inviteCode);
        //邀请的人数
        List<TbMnUser> tbMnUserList = tbMnUserService.list(inVitequeryWrapper);

        if (null != tbMnUserList && tbMnUserList.size() > 0) {
            for (TbMnUser mnUser : tbMnUserList) {
                QueryWrapper userWalletQueryWrapper = new QueryWrapper();
                userWalletQueryWrapper.eq("user_id", mnUser.getId());
                userWalletQueryWrapper.eq("pay_from", PayTypeConstant.PAYFORM_REBATE);
                List<TbUserWalletDetail> tbUserWalletDetailList = tbUserWalletDetailService.list(userWalletQueryWrapper);
                for (TbUserWalletDetail tbUserWalletDetail : tbUserWalletDetailList) {
                    profit.add(tbUserWalletDetail.getBalance());
                }
                inivate_number += 1;
                able_map.put("profit", profit);
                able_map.put("inivate_number", inivate_number);
            }
        }

    }

    @Override
    public TbUserGameBuiding getOneAndUpgradeConfig(String user_id) {
        return this.baseMapper.getOneAndUpgradeConfig(user_id);
    }

    //TODO  盖楼初次创建  需要不需要花费SQT ，是否需要写一个开关量，如果需要则开启开关
    @Override
    public Result<?> createBuilding(String user_id, Integer type) {
        QueryWrapper buildingQuery = new QueryWrapper();
        buildingQuery.eq("user_id", user_id);
        List<TbUserGameBuiding> tbUserGameBuidingList = this.baseMapper.selectList(buildingQuery);
        if (null != tbUserGameBuidingList && tbUserGameBuidingList.size() > 0) {
            return Result.error("已经建过");
        }

        QueryWrapper tbUserUpgradeConfigQuery = new QueryWrapper();
        tbUserUpgradeConfigQuery.eq("sort", 0);
        tbUserUpgradeConfigQuery.eq("type", type);

        TbUserUpgradeConfig tbUserUpgradeConfig = tbUserUpgradeConfigService.getOne(tbUserUpgradeConfigQuery);
        if (null == tbUserUpgradeConfig) {
            return Result.error("升级规则配置错误");
        }
        TbUserSqt tbUserSqt = tbUserSqtService.getOneByUserId(user_id);
        if (null != tbUserSqt) {
            //自己的资产
            TbMnUser tbMnUser = tbMnUserService.getById(user_id);

           // if (verifyInviteesNumber(user_id, tbUserUpgradeConfig)) return Result.ok("邀请人不足，邀请好友加入吧!");

            if (verifyBalanceStatus(tbUserUpgradeConfig, tbUserSqt, tbMnUser)) return Result.ok("资金不足，努力赚钱吧!");

            if (saveGameBuilding(user_id, type, tbUserUpgradeConfig, tbMnUser)) return Result.ok("构建成功");
        }
        return Result.error("盖楼失败");

    }

    @Override
    public Result<?> getGameBuildingData(String user_id, Integer type) {

        Map<String, Object> resultMap = new HashMap<>();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", user_id);
        queryWrapper.eq("type", type);
        TbUserGameBuiding tbUserGameBuiding = getOne(queryWrapper);
        if (null == tbUserGameBuiding) {
            resultMap.put("state", 0);
            resultMap.put("msg", "没有盖楼信息");
            return Result.ok(resultMap);
        }
        String gradeId = tbUserGameBuiding.getGrade();
        TbUserUpgradeConfig tbUserUpgradeConfig = tbUserUpgradeConfigService.getById(gradeId);
        //今日产出SQT
        if (type == 1) {
            BigDecimal sqt_totalNumber = tbUserSqtDetailService.getUserSQTByToday(user_id);
            resultMap.put("sqt_totalNumber", sqt_totalNumber);
        }
        //人民币的 今日分红信息
        if (type == 2) {
            BigDecimal wallet_totalNumber = tbUserWalletDetailService.getUserWalletByToday(user_id);
            resultMap.put("wallet_totalNumber", wallet_totalNumber);
        }
        resultMap.put("tbUserGameBuiding", tbUserGameBuiding);
        //升级规则和速率
        resultMap.put("tbUserUpgradeConfig", tbUserUpgradeConfig);
        resultMap.put("state", 1);

        return Result.ok(resultMap);
    }

    @Override
    public  Result<?> give100Hours(String user_id) {

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", user_id);

        TbUserGameBuiding tbUserGameBuiding = this.getOne(queryWrapper);
        if (null == tbUserGameBuiding) {
            return Result.error("请先盖楼");
        }
        TbMnUser tbMnUser = this.tbMnUserService.getById(user_id);
        if (tbMnUser.getIsGive100() == 0) {

            int businessHours = tbUserGameBuiding.getBusinessHours();
            tbUserGameBuiding.setBusinessHours(businessHours + 100);
            if (updateById(tbUserGameBuiding)) {
                tbMnUser.setIsGive100(1);
                if (this.tbMnUserService.updateById(tbMnUser)) {
                    return Result.ok("赠送成功");
                }
            }

        } else {
            return Result.error("已经赠送过营业时间");
        }
        return Result.error("赠送100分钟营业时间");
    }

    private boolean verifyBalanceStatus(TbUserUpgradeConfig tbUserUpgradeConfig, TbUserSqt tbUserSqt, TbMnUser tbMnUser) {
        BigDecimal bigDecimal = tbUserSqt.getBalance();
        int profitNumber = tbUserUpgradeConfig.getProfitNumber();
        if (tbMnUser.getIsFirstBuilding() == 0) {
            profitNumber = profitNumber / 2;
        }

        BigDecimal profitNumberDecimal = new BigDecimal(profitNumber);
        int flag = profitNumberDecimal.compareTo(bigDecimal);
        if (flag >= 0) {
            return true;
        }
        BigDecimal newBalance = tbUserSqt.getBalance().subtract(new BigDecimal(profitNumber));
        tbUserSqt.setBalance(newBalance);
        //更新资产//增加日志明细
       // saveSqtDetail(tbUserSqt, new BigDecimal(profitNumber), newBalance);
        return false;
    }

    private boolean verifyInviteesNumber(String user_id, TbUserUpgradeConfig tbUserUpgradeConfig) {
        Integer inviteesNumber = tbMnUserService.getInviteesNumberByInviteCode(user_id);
        if (inviteesNumber < tbUserUpgradeConfig.getInvateNumber()) {
            return true;
        }
        return false;
    }

    private boolean saveGameBuilding(String user_id, Integer type, TbUserUpgradeConfig tbUserUpgradeConfig, TbMnUser tbMnUser) {
        TbUserGameBuiding tbUserGameBuiding = new TbUserGameBuiding();
        tbUserGameBuiding.setBusinessHours(0);
        tbUserGameBuiding.setGrade(tbUserUpgradeConfig.getId());
        tbUserGameBuiding.setGradeName(tbUserUpgradeConfig.getRemark());
        tbUserGameBuiding.setIntegral(0);
        tbUserGameBuiding.setState(1);
        tbUserGameBuiding.setCompleteDay(40);
        tbUserGameBuiding.setCurrentDay(0);
        tbUserGameBuiding.setUserId(user_id);
        //24个小时 24*60=1440分钟
        tbUserGameBuiding.setTotalConsumeHours(24 * 60);
        tbUserGameBuiding.setType(type);
        if (this.save(tbUserGameBuiding)) {
            tbMnUser.setIsFirstBuilding(1);
            if (tbMnUserService.updateById(tbMnUser)) {
                return true;
            }
        }
        return false;
    }

    private void saveSqtDetail(TbUserSqt tbUserSqt, BigDecimal balance, BigDecimal newBalance) {
        TbUserSqtDetail tbUserSqtDetail = new TbUserSqtDetail();
        tbUserSqtDetail.setPayFrom(PayTypeConstant.PAYFORM_GAME_BUILDING);
        tbUserSqtDetail.setPayType(PayTypeConstant.PAYTYPE_EXPEND);
        tbUserSqtDetail.setPayNumber(balance);
        tbUserSqtDetail.setPayAfterNumber(newBalance);
        tbUserSqtDetail.setSqtId(tbUserSqt.getId());
        tbUserSqtDetail.setUserId(tbUserSqt.getUserId());
        if (tbUserSqtDetailService.save(tbUserSqtDetail)) {
            tbUserSqtService.updateById(tbUserSqt);
        }
    }
}
